package leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述:括号生成 回溯
 *
 * @author Madison You
 * @created 22:13
 */
public class Mid_22_GenerateParenthesis {

    public static void main(String[] args) {
        List<String> strings = new Mid_22_GenerateParenthesis().generateParenthesis(3);
        for (String string : strings) {
            System.out.println(string);
        }
    }

    List<String> list = new ArrayList<>();

    public List<String> generateParenthesis(int n) {
        back(n, 0, 0, new StringBuilder());
        return list;
    }

    private void back(int n, int open, int close, StringBuilder sb) {
        if (sb.length() == n * 2) {
            list.add(sb.toString());
        }
        if (open < n) {
            sb.append("(");
            back(n, open + 1, close, sb);
            sb.deleteCharAt(sb.length() - 1);
        }
        if (close < open) {
            sb.append(")");
            back(n, open, close + 1, sb);
            sb.deleteCharAt(sb.length() - 1);
        }
    }

}
